package com.yuzi.service.systemSer;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yuzi.common.Constant;
import com.yuzi.model.systemMo.SysRole;
import com.yuzi.model.systemMo.SysUser;
import com.yuzi.model.systemMo.SysUserRole;
import com.yuzi.service.BaseSer.BaseService;
import com.yuzi.utils.DateUtils;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SysUserService extends BaseService {

    private SysUser sysUserDao;

    private SysUserRole sysUserRoleDao;

    private SysRole sysRoleDao;

    /**
     *
     * @param pageNumber
     * @param pageSize
     * @param userSele
     * @param userNameSele
     * @return 根据页数条数返回查询用户
     */
    public Page<SysUser> findAllSysUser(int pageNumber, int pageSize,String userSele,String userNameSele){
        return sysUserDao.findAllSysUser(pageNumber, pageSize,userSele,userNameSele);
    }

    public Page<SysUser> findSysUserByroleId(int pageNumber, int pageSize,int roleid){
        return sysUserDao.findSysUserByroleId(pageNumber, pageSize,roleid);
    }

    /**
     * @return 查询所有的用户
     */
    public List<SysUser> findAllSysUser(){
        return sysUserDao.findAllSysUser();
    }

    //批量删除
    public Map<String, String> batchDelSysUser(String param){
    	String[] params=param.split(",");
        final Map<String ,String> map = new HashMap<>();
        /*for (String id : params) {
			if(Integer.parseInt(id)==Constant.SysConfig.sys_user_id) {
				 map.put("flag","false");
	             map.put("msg","禁止删除该用户");
	             return map;
			}
		}*/
        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            	String ids="(";
            	for (String id : params) ids+=id+",";
            	ids=ids.substring(0, ids.length()-1);
            	ids+=")";
                boolean isDelete = sysUserDao.batchDelSysUser(ids);
                //将权限表中的关联关系删掉（sys_user_role）,通过user_id
                int affect = sysUserRoleDao.deleteSysUserRoleByUserIds(ids);
                if (isDelete && (affect==params.length)){
                    map.put("flag","true");
                    map.put("msg","批量删除成功");
                    return true;
                }else{
                    map.put("flag","false");
                    map.put("msg","批量删除失败");
                    return false;
                }
            }
        });
        return map;
    }
    
    

    public Map<String, String> addSysUser(SysUser sysUser,int roleId){

        final Map<String ,String> map = new HashMap<>();
        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                //添加用户,加密
                PasswordService svc = new DefaultPasswordService();
                String password = svc.encryptPassword(sysUser.getStr("password"));
                sysUser.set("password",password);
                sysUser.set("createtime",DateUtils.getCurrentDateTime());
                int id =  sysUserDao.addSysUser(sysUser);

                if (id >0){
                    //添加权限
                    boolean flag = sysUserRoleDao.addSysUserRole(id,roleId);
                    if (flag) {
                        map.put("flag","true");
                        map.put("res", "用户添加成功");
                        return true;
                    }else{
                        map.put("flag","false");
                        map.put("res","添加失败，该权限已存在");
                        return false;
                    }
                }else {
                    map.put("flag","false");
                    map.put("res","该用户添加失败");
                    return false;
                }
            }
        });
        return map;
    }

    public boolean updateUserInfo(String oldPassword, String newPassword){
        int userId = super.getCurrentUser().get("id");
        SysUser sysUser = sysUserDao.findById(userId);

        PasswordService svc = new DefaultPasswordService();
        boolean flag = svc.passwordsMatch(oldPassword,sysUser.get("password"));
        //判断原始密码是否正确
        if (flag){
            sysUser.set("plaintext",newPassword);
            sysUser.set("password",svc.encryptPassword(newPassword));
            return sysUser.update();
        }else{
            return false;
        }
    }

    public Map<String, String> deleteSysUser(int id){
        final Map<String ,String> map = new HashMap<>();

        if (id == Constant.SysConfig.sys_user_id){
            map.put("flag","false");
            map.put("msg","禁止删除该用户");
            return map;
        }

        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {

                boolean isDelete = sysUserDao.deleteById(id);
                if (isDelete){
                    //将权限表中的关联关系删掉（sys_user_role）,通过user_id
                    sysUserRoleDao.deleteSysUserRoleByUserId(id);
                    map.put("flag","true");
                    map.put("msg","删除成功");
                    return true;
                }else{
                    map.put("flag","false");
                    map.put("msg","删除失败");
                    return false;
                }
            }
        });
        return map;
    }

    public SysUser findUserById(int userId){
        return sysUserDao.findById(userId);
    }

    public Record findUserAndRoleByUserId(int userId){
        return sysUserDao.findUserAndRoleByUserId(userId);
    }

    public boolean updateSysUserStatusById(int userId,String status){
        SysUser sysUser = findUserById(userId);
        sysUser.set("status",status);
        return sysUser.update();
    }

    public Map<String ,String> updateSysUserAndRole(SysUser sysUser,int roleId){

        final Map<String ,String> map = new HashMap<>();
        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                SysUser oldSysUser = sysUserDao.findById(sysUser.getInt("id"));
                oldSysUser._setAttrs(sysUser);  //向数据库中更新字段时，采用这个，不能用put
                boolean isOk = sysUserDao.updateSysUser(oldSysUser);
                //将权限表中的关联关系删掉（sys_user_role）,通过user_id
                sysUserRoleDao.deleteSysUserRoleByUserId(oldSysUser.getInt("id"));
                boolean isAdd = sysUserRoleDao.addSysUserRole(oldSysUser.getInt("id"),roleId);
                if (isOk && isAdd){
                    map.put("flag","true");
                    map.put("msg","更新成功");
                    return true;
                }else{
                    map.put("flag","false");
                    map.put("msg","更新失败");
                    return false;
                }
            }
        });
        return map;
    }

    public Map<String ,List> getChatUserList(){
        Integer userId = super.getCurrentUser().getInt("id");
        List<Record> userList = sysUserDao.findRolesToUsers(userId);
        List<SysRole> roleList = sysRoleDao.findSysRoleByCondition(null);

        Map<String ,List> map = new HashMap<>();
        map.put("roleList",roleList);
        map.put("userList",userList);
        return map;
    }
}
